package com.example.uidemo.adapter;

import android.content.Context;
import android.support.annotation.NonNull;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.example.uidemo.R;
import com.example.uidemo.dto.Fruit;

import java.util.List;

/**
 * Created by Administrator on 2018/1/22.
 */

public class FruitAdapter extends ArrayAdapter<Fruit> {

    private int resourceId;


    public FruitAdapter(Context context, int resource, List<Fruit> objects) {
        super(context, resource, objects);
        resourceId = resource;
    }


    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        Fruit fruit = getItem(position);  // 获取当前的fruit实例
        View view;
        ViewHolder viewHolder;
        if(convertView == null){
            view = LayoutInflater.from(getContext()).inflate(resourceId,parent,false); // 加载我们的布局
            viewHolder = new ViewHolder();
            viewHolder.fruitImage = (ImageView) view.findViewById(R.id.fruit_image);
            viewHolder.fruitName = (TextView) view.findViewById(R.id.fruit_text);
            view.setTag(viewHolder);
        }else{
            view = convertView;
            viewHolder = (ViewHolder) view.getTag();
        }
/*        View view = LayoutInflater.from(getContext()).inflate(resourceId,parent,false);  // 获取Layout
        ImageView img = (ImageView) view.findViewById(R.id.fruit_image);
        TextView btn = (TextView) view.findViewById(R.id.fruit_text);
        img.setImageResource(fruit.getImageId());
        btn.setText(fruit.getName());*/

        viewHolder.fruitImage.setImageResource(fruit.getImageId());
        viewHolder.fruitName.setText(fruit.getName());
        return view;
    }

    class ViewHolder{
        ImageView fruitImage;
        TextView fruitName;

        public ImageView getFruitImage() {
            return fruitImage;
        }

        public void setFruitImage(ImageView fruitImage) {
            this.fruitImage = fruitImage;
        }

        public TextView getFruitName() {
            return fruitName;
        }

        public void setFruitName(TextView fruitName) {
            this.fruitName = fruitName;
        }
    }
}
